package com.ruoyi.classai.api;

import cn.hutool.jwt.JWT;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.classai.domain.EwcCourseGrouping;
import com.ruoyi.classai.domain.dto.StudentLoginDto;
import com.ruoyi.classai.domain.vo.StudentGroupVo;
import com.ruoyi.classai.service.IEwcCourseGroupingService;
import com.ruoyi.classai.service.IEwcStudentGroupService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.ThirdSession;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 学生端小组联系和课后作业接口
 * @author zsp
 * @date 2025年03月18日 06：34
 */
@Slf4j
@Validated
@RestController
@Tag(name = "学生端小组联系和课后作业接口")
@RequestMapping("/api/studentClient")
public class StudentClientApi {

    @Autowired
    private IEwcStudentGroupService iEwcStudentGroupService;

    @Autowired
    private IEwcCourseGroupingService iEwcCourseGroupingService;

    @Autowired
    private RedisService redisService;
    /**
     * 查询学生分组信息
     * @param studentLoginDto
     * @return AjaxResult
     */
    @Operation(summary = "学生登录")
    @PostMapping("/studentLogin")
    public AjaxResult getStudentGroupInfo(@Valid @RequestBody StudentLoginDto studentLoginDto) {
        StudentGroupVo studentGroupVo = null;
        if ("groupPractice".equals(studentLoginDto.getPracticeType())) {
            studentGroupVo = iEwcStudentGroupService.getStudentGroupInfo(studentLoginDto);
        }else if("courseBackPractice".equals(studentLoginDto.getPracticeType())){
            return AjaxResult.error("暂未开通");
        }else{
            return AjaxResult.error("练习类型选择有误");
        }
        if (Objects.isNull(studentGroupVo)) {
            return AjaxResult.error("学号有误");
        }
        String token = JWT.create()
                .setPayload("timestamp", System.currentTimeMillis())//过期时间
                .setPayload("uid", studentGroupVo.getStudentId())//用户id
                .setKey(Constants.AES_KEY.getBytes())//授权密钥
                .sign();
        ThirdSession thirdSession = new ThirdSession();
        thirdSession.setId(studentGroupVo.getStudentId());
        redisService.setCacheObject(CacheConstants.API_TOKEN_CACHE + token, JSONObject.toJSONString(thirdSession), 30L, TimeUnit.DAYS);
        log.info("学生登录成功");
        JSONObject resultJson = new JSONObject();
        resultJson.put("token", token);
        resultJson.put("studentGroupInfo", studentGroupVo);
        return AjaxResult.success("登录成功", resultJson);
    }
}
